﻿using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using ActivateYourGlutes.Helpers;
using ActivateYourGlutes.Infrastructure;
using ActivateYourGlutes.Model;
using ActivateYourGlutes.Model.Contracts;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.ServiceLocatorAdapter;
using Body=ActivateYourGlutes.Model.Contracts.Body;

namespace ActivateYourGlutes
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("favicon.ico");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            ModelBootstrapper.Initialise();
            RegisterRoutes(RouteTable.Routes);

            ConfigureContainer();
            ControllerBuilder.Current.SetControllerFactory(new CommonServiceLocatorControllerFactory());
            ModelBinders.Binders.Add(typeof(DateTime), new LocalisedDateTimeBinder());
            ModelBinders.Binders.Add(typeof(DateTime?), new LocalisedDateTimeBinder());
            ModelBinders.Binders.Add(typeof(Model.Contracts.Body), new BodyBinder());
        }

        private static void ConfigureContainer()
        {
            IUnityContainer container = new UnityContainer();

            UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            configuration.Containers.Default.Configure(container);

            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
        }
    }
}